/*
 * GomokuOnline javascript Class
 * Thanks for Livid, his gomoku for iPhone's UI is the original of this game.
 * Version 1.02 (20:30 10/09/2009)
 */

var $ = function(i){
  return eval(document.getElementById(i)); 
}
var isIE=!+'\v1';
/*
 * GomokuUI Class is the User Interface of Gomokuonline.
 */
var GomokuUI = function(){
    /* if stone down that perform */
  var _movStoneCallBack;
    /* Draw stone target */
  this.init = function(){
    this._bg="bg";
    this._frame=isIE?"chessFrameIE":"chessFrame";
    this._dot=isIE?"dotIE":"dot";
    this._downContent="downContent";
    this._mainChessCSS=isIE?"mainChessIE":"mainChess";
  }
  this.drawStonepointer = function(){
    // Draw stones
    var _span=[];
    var i=0;
    for(x=0;x<15;x++){
      for(y=0;y<15;y++){
        _span[i]=document.createElement("span");
        _span[i].setAttribute("id",x+"_"+y);
        _span[i].onclick = function(){
          imoveStone(this);
       }
       $(this._dot).appendChild(_span[i]);
       i++;
      }
    }
  }
  // u can use imoveStone to display local player's stone
  var imoveStone = function(stone){
    if(!this._locked_1)
    if(!!!stone.className){
      //_movStoneCallBack(stone);
      if($("flag").value==0)
        stone.className="white";
      else
        stone.className="black";
    _movStoneCallBack(stone);
    }
  }
  
  this.setmovStoneCallBack = function(_callback){
    _movStoneCallBack = _callback;
  }
};

GomokuUI.prototype = {
  /* background div */
  _bg:null,
  /* frame div */
  _frame:null,
  /* stone area */
  _dot:null,
  /* control area */
  _downContent:null,
  /* control area : left and right */
  _lArea:null,
  _rArea:null,
  /* player locked */
  _locked_1:null,
  /* set background, frame and dot's id. and program will use those element to
   * generate GUI..
   */
   _bg:null,
   _frame:null,
   _dot:null,
   _downContent:null,
   _mainChessCSS:null,
  //set locked
  setLocked:function(){
    _locked_1 = 1;
  },
  //set unlocked
  unLocked:function(){
    _locked_1 = 0;
  },
  //addContent to _bg
  addContent:function(object){
    $(this._bg).appendChild(object);
  },
  //Draw gomoku board
  drawGomokuboard:function(){
    var _div=[];
    var i=0;
    var __frame = document.createElement("div");
    __frame.id = this._frame;
    $(this._bg).appendChild(__frame);
    var __dot = document.createElement("div");
    __dot.id = this._dot;
    //__frame.appendChild(__dot);
    $(this._bg).appendChild(__dot);
    for(x=0;x<14;x++){
      for(y=0;y<14;y++){
        _div[i]=document.createElement("div");
          _div[i].className=this._mainChessCSS;
      $(this._frame).appendChild(_div[i]);
        i++;
        }
    }
    i=0;
    this.putContainer();
  },

  // Public function. u can use tmovStone to display another player's stone
  tmoveStone:function(x_y){
    var stone = $(x_y);
    if(!!!stone.className){
      if($("flag").value==1)
        stone.className="white";
      else
        stone.className="black";
      return 1;
    }
    else
    {
      return 0;
    }
  },

  /* create button on the down control (downbut) 
   * id     : string   -> id of the button
   * imgurl : string   -> picture's url.
   * title  : string   -> point on and show text
   * area   : int      -> 1.left : 2.right
   * src    : string   -> show the string, when the mouse over the picture
   * todo   : function -> onclick and to do.
   * width  : int      -> width
   * status : int      -> 1.normal 2.actived
   */
  createButton:function(id,imgurl,area,status,title,todo,_width){
    if(!!$(this._downContent)){
      var _button = document.createElement("a");
      _button.innerHTML =title;
      _button.id = id;
      _button.setAttribute("title",title);
      _button.style.backgroundImage = "url("+imgurl+")";
      (!!!_width)? _width ="71px" : _width =_width+"px";
      _button.style.width=_width;
      _button.href="javascript:void(0)";
      _button.className=(!status)?"smallButton":"smallButtonAct";
      _button.onclick=todo;
      switch(area){
        case 1:_button.style.cssFloat="left";
               _button.style.marginLeft="8px";
               _lArea.appendChild(_button);
        break;
        case 2:_button.style.cssFloat="right";
               _button.style.marginRight="8px";
               _rArea.appendChild(_button);
      }
      return _button;
    }
  },
  /* put button container in _downContent */
  putContainer:function(){
    var Container = document.createElement("div");
    Container.setAttribute("id",this._downContent);
    $(this._bg).appendChild(Container);
    /* left Area */
    _lArea = document.createElement("span");
    _lArea.id = "lArea";
    _lArea.className="lArea";
   
    /* right Area */
    _rArea = document.createElement("span");
    _rArea.id = "rArea";
    _rArea.className="rArea";
    if(isIE){
      _lArea.style.textAlign = "left";
      _rArea.style.textAlign = "right";
    }
    $(this._downContent).appendChild(_lArea);
    $(this._downContent).appendChild(_rArea);
  },
  /* refresh stones*/
  refresh:function(){
    for(x=0;x<15;x++)
      for(y=0;y<15;y++)
        $(x+"_"+y).className = "";
        
  },
  //remove Button by id, id -> string
  removelAreaButton:function(id){
    $("lArea").removeChild($(id));
  },
  removerAreaButton:function(id){
    $("rArea").removeChild($(id));
  }
};
// PopUp
GomokuUI.prototype.PopUp = function(){
  var _cover = document.createElement("div");
  var _Popup = document.createElement("div");
  var _span = document.createElement("span");
  var _spancencel = document.createElement("span");
  var _cencelImg;
  var _popupImgurl,_popupImgheight;
  var timer1,timer2;
  var _firstRun=0;
  var _todo,_todoflag;
  /*isPopup 1-> popup 0->unpopup */
  var isPopup;
  /* onPopup is a Button container to fix ie */
  var _onPopup = document.createElement("div");
  this.setPopupImgurl = function(popupImgurl,popupImgheight){
    _popupImgurl = popupImgurl;
    _popupImgheight = popupImgheight;
  }
  this.setCencelImg = function(imgurl){
      _cencelImg = imgurl;
  }
  this.show = function(){
    showPopup(_firstRun);
    _firstRun = 1;
  }
  
  /*function showCover(){
    _cover = document.createElement("div");
    _cover.className="cover";
    $(_bg).appendChild(_cover);
  }*/
  
  //popup Animation effects
  function showPopup(_firstRun){
    if(!isPopup){
      isPopup = 1;
      if(!_firstRun){
        /* add cencel button */
        var _cencelbutton = document.createElement("a");
        _cencelbutton.className = "bigButton";
        _cencelbutton.innerHTML = "Cencel";
        _cencelbutton.setAttribute("title","Cencel");
        _cencelbutton.style.backgroundImage = "url("+_cencelImg+")";
        _cencelbutton.href = "javascript:void(0)";
        _cencelbutton.onclick = function(){_cencel()}
        _spancencel.appendChild(_cencelbutton);   
      }
        /* end */
      _span.className="popupContainer";
      _spancencel.className = "popupContainerCencel";
      _Popup = document.createElement("div");
      // set background image
      // IE FIX
      if(isIE)
        _Popup.style.filter="progid:DXImageTransform.Microsoft.\
          AlphaImageLoader(src='"+_popupImgurl+"')";
      else{
        _Popup.style.backgroundImage="url("+_popupImgurl+")";
      }

      _Popup.className="popup";
      _onPopup.className="popup";
      _Popup.style.marginTop = _popupImgheight+"px";
      _onPopup.style.marginTop = _popupImgheight+"px";
      $("bg").appendChild(_Popup);
      $("bg").appendChild(_onPopup);
      _onPopup.appendChild(_span);
      _onPopup.appendChild(_spancencel);
       //mov(_Popup);
      timer1 = setInterval(mov,10);
    }
  }
  //popup Animation effects
  var mov = function(){
    var _px = parseInt(_Popup.style.marginTop)||0;
    //var _s = _cover.style.opacity;
    if(_px>0){
      _px -= 10;
      _onPopup.style.marginTop = _px+"px";
      _Popup.style.marginTop = _px+"px";
    }else{
      clearInterval(timer1);
      //showCover();
    }
  }
  // popup quit
  var _cencel= function(){
    if(isPopup){
	  try{clearInterval(timer1)}catch(e){};
      isPopup = 0;
      timer1=setInterval(goOut,5);
    }
  }
  
  this.cencel = function(){
      _cencel();
  }
  //go out there!
  function goOut(){
    var _px = parseInt(_Popup.style.marginTop)||0;
    //var _s = _cover.style.opacity;
    if(_px<250){
      _px += 10;
      _onPopup.style.marginTop = _px+"px";
      _Popup.style.marginTop = _px+"px";
    }else{
      clearInterval(timer1);
      _onPopup.removeChild(_span);
      _onPopup.removeChild(_spancencel);
      $("bg").removeChild(_Popup);
      $("bg").removeChild(_onPopup);
      _span = document.createElement("span");
      if(_todoflag){
        _todoflag=0;
        _todo();
     }
    }
  }
  //use to near Popup
  this.goOutAndDo = function(todo){
      _todo = todo;
      _todoflag = 1;
      _cencel();
  }

  /* createButton of Popup
   * imgurl : string    -> button picture's url
   * title  : string    -> point on and show text
   * todo   : function  -> onclick and to do.
   */
  this.createButton = function(imgurl,title,todo){
    var _button = document.createElement("a");
    _button.className = "bigButton";
    _button.innerHTML = title;
    _button.setAttribute("title",title);
    _button.style.backgroundImage = "url("+imgurl+")";
    _button.href = "javascript:void(0)";
    _button.onclick = function(){todo()};
    _span.appendChild(_button);
   }
  /* create a Span tab
   * id        : string -> set Span's id
   * classname : string -> set Span's className
   * innerhtml : string -> set HTML
   */
  this.createSpan = function(id,classname,innerhtml){
    var __span = document.createElement("span");
    __span.id = id;
    __span.className = classname;
    __span.innerHTML = innerhtml;
    _span.appendChild(__span);
    return __span;
  }
  this.addElement = function(object){
    _span.appendChild(object);
  }
};

/* Show Next Screen */
GomokuUI.prototype.Nextscreen = function(){
  var _Screen = document.createElement("div");
  var _Title = document.createElement("div");
  var _Content = document.createElement("div");
  var _spancencel = document.createElement("span");
  var _cencelImg;
  var _titleImgurl;
  var timer1;
  var _firstRun=0;
  var _todo,_todoflag;
  /*isShow 1-> Showed 0->isShow */
  var isShow;
  this.setTitleImgurl = function(titleImgurl){
    _titleImgurl = titleImgurl;

  }
  this.setCencelImg = function(imgurl){
      _cencelImg = imgurl;
  }
  this.show = function(){
    showScreen(_firstRun);
    _firstRun = 1;
  }
   //Screen Animation effects
  function showScreen(_firstRun){
    if(!isShow){
      isShow = 1;
      if(!_firstRun){
        /* add cencel button */
        _Screen.id = "Nextscreen";
        var _cencelbutton = document.createElement("a");
        _cencelbutton.className = "smallButtonAct";
        _cencelbutton.innerHTML = "Dismiss";
        _cencelbutton.setAttribute("title","Dismiss");
        _cencelbutton.style.backgroundImage = "url("+_cencelImg+")";
        _cencelbutton.style.width="71px";
        _cencelbutton.style.cssFloat="left";
        
        _cencelbutton.style.marginLeft="8px";
        _cencelbutton.href = "javascript:void(0)";
        _cencelbutton.onclick = function(){_cencel()};
        _spancencel.className = "lArea";
        if(isIE) _spancencel.style.textAlign = "left";
        _spancencel.appendChild(_cencelbutton); 
      }
      _Content.className = "content";
      _Title.className = "title";
      _Title.style.backgroundImage = "url("+_titleImgurl+")";
      _Title.style.top="0px";
      _Screen.style.marginLeft ="300px";
      _Screen.appendChild(_Title);
      _Screen.appendChild(_spancencel);
      _Screen.appendChild(_Content);
      $("show").appendChild(_Screen);
      // start mov
      timer1 = setInterval(mov,10);
    }
  }
  //screen Animation effects
  var mov = function(){
    var _px = parseInt(_Screen.style.marginLeft)||0;
    //var _s = _cover.style.opacity;
    if(_px>0){
      _px -= 10;
      $("bg").style.left = (_px-300)+"px";
      _Screen.style.marginLeft = _px+"px";
    }else{
      clearInterval(timer1);
      //showCover();
    }
  }
  // popup quit
  var _cencel= function(){
    if(isShow){
	  try{clearInterval(timer1)}catch(e){};
      isShow = 0;
      timer1=setInterval(goOut,10);
    }
  }
  
  this.cencel = function(){
      _cencel();
  }
  //go out there!
  function goOut(){
    var _px = parseInt(_Screen.style.marginLeft)||0;
    //var _s = _cover.style.opacity;
    if(_px<300){
      _px += 10;
      $("bg").style.left =(_px-300)+"px";
      _Screen.style.marginLeft = _px+"px";
    }else{
      clearInterval(timer1);
      _Screen.removeChild(_Title);
      _Screen.removeChild(_Content);
      _Screen.removeChild(_spancencel);
      $("show").removeChild(_Screen);
      _Content = document.createElement("div");
      if(_todoflag){
        _todoflag=0;
        _todo();
     }
    }
  }
  //use to near Popup
  this.goOutAndDo = function(todo){
      _todo = todo;
      _todoflag = 1;
      _cencel();
  }
  this.addElement = function(object){
    _Content.appendChild(object);
  }
};


/**
 * GomokuOnline Class is a controller.
 */
function GomokuOnline(){
  var gomokuServer;
  /* images Website */
  var _imgSite;
  /* httpRequest */
  var req;
  /* random number of server */
  var rdnum;
  var gui = new GomokuUI();
  var __times;
  //player
  var __mystone;
  var __opstone;
  var playing;
  /* only one random number to distinguish client */
  var rdnum_textfield;
  /* errMessage */
  var _errMessage;
  /* gui.PopUp() */
  var _p;
  /* gui.Nextscreen() */
  var _ns;
  /* get Next Timer*/
  var getNextTimer,waitForjoinTimer,stonedownTimer;
  var _ = this;
  /* set the game Server */
  this.setServeraddress = function(address){
    gomokuServer = address;
  }
  /* set image server */
  this.setimgSite = function(imgSite){
    _imgSite = imgSite;
  }
  /* Create Player Array */
  this.createPlayer = function(){
    var arr = new Array(15);
    for(var i=0;i<15;i++){
      arr[i] = new Array(15);
    }
    return arr;
  }
  /*
   * Run GomokuOnline.
   * Initialize UI and do cycle of program
   */
  this.Run = function(bg,frame,dot,downContent){

  /* initialize the GUI */
    gui.init();
    gui.drawGomokuboard();
    gui.drawStonepointer();
    /*var btnRetract = gui.createButton(_imgSite+"enbutRetract.png",
      1,1,"Retract",function(){alert("This is demo")});*/
    var btnHelp = gui.createButton("btnHelp",_imgSite+"zhcnbutHelp.png",
      1,0,"Help",function(){showHelp()},45);
    var btnNamegame = gui.createButton("btnNewgame",_imgSite+"zhcnbutNewgame.png",
      2,0,"New game",function(){startaNewgame()});
    gui.setmovStoneCallBack(iMov);
    /* set _p  */
    _p = new gui.PopUp();
    _p.setCencelImg(_imgSite+"zhcnbigButCancel.png");
    /* set _ns */
    _ns = new gui.Nextscreen();
    _ns.setCencelImg(_imgSite+"zhcnbutDismiss.png");
    
    //set locked
    gui.setLocked();
  }
  // I down stone
  var iMov = function(stone){
    gui.setLocked();
    var x_y = stone.id;
    var url = "?rdnum=" + $("rdnum").value + "&flag=" + $("flag").value + 
    "&stone=" + x_y;
    var stone = x_y.split("_");
    stone = {
      x:parseInt(stone[0],10),
      y:parseInt(stone[1],10)
    };
    // recode
    __mystone[stone.x][stone.y] = 1;
    playing = __mystone;
    stonedownTimer=setInterval(function(){oniMov(url)},1000);
    if(judge(stone,$("flag").value)) return;
    getNext();
  }
  var oniMov = function(url){
      var ts = Math.round(new Date().getTime() / 1000);

    _IG_FetchContent(gomokuServer+"stonedown"+url+ "&t="+ts,oniMovstat,
      {refreshInterval:0});
  }
  var oniMovstat = function(responseText){
    if(responseText=="1"){
      clearInterval(stonedownTimer);
    }
  }
  /*
   * n -> coordinate of stone(x,y)
   * stone -> Write or black
   */
  var judge = function(n,stone){
    if(success(n))
    {
      gui.setLocked();
      if(stone==1){
        //black Win!
        var res = document.createElement("span");
        res.id = "res";
        res.className = "content";
        res.innerHTML = "<img src='"+_imgSite+"zhcnblackwin.png'/>";
        gui.addContent(res);
      }
      else{
        //white Win!
        var res = document.createElement("span");
        res.id = "res";
        res.className = "content";
        res.innerHTML = "<img src='"+_imgSite+"zhcnwhitewin.png'/>";
        gui.addContent(res);
      }
      gui.removelAreaButton("btnGiveup");
      $("btnNewgame").className = "smallButton";
      $("btnNewgame").onclick = function(){startaNewgame()};
      return 1;
    }
    return 0;
  }
  var success = function(n){
    var p = playing;
    var line = [];
    //-
    line[0] = p[n.x].join(',');
    //|
    line[1] = function(){
      var a = [];
        for(var i=0;i<p.length;i++)
          a.push(p[i][n.y]);
          return a.join(',');
        }();
    // top left to down right slant \
    line[2] = function(){
      var postionDiff = n.y - n.x;
      var a = [];
      for(var i=0;i<p.length;i++){
        for(var j=0;j<p[i].length;j++){
          if(j - i == postionDiff){
            a.push(p[i][j]);
            break;
          }
        }
      }
      return a.join(',');
    }();
    // down left to top right slant /
    line[3] = function(){
      var postionSum = n.y + n.x;
      var a = [];
      for(var i=0;i<p.length;i++){
        for(var j=0;j<p[i].length;j++){
          if(j + i == postionSum){
            a.push(p[i][j]);
            break;
          }
        }
      }
        return a.join(',');
    }();
    return (line.join('$')).indexOf('1,1,1,1,1')>-1;
  }
    /* get player's next stone */
  var getNext = function(){
    var loading = document.createElement("span");
    loading.id = "loading";
    loading.className = "content";
    loading.innerHTML = "<img src='"+_imgSite+"loading.gif'/>"+
    "等待对方下子 ...";
    gui.addContent(loading);
    //set Give up locked
    $("btnGiveup").className = "smallButtonAct";
    $("btnGiveup").onclick = "javascript:void(null);";
    var url = "?rdnum=" + $("rdnum").value + "&flag=" + $("flag").value;
    getNextTimer = setInterval(function(){onNext(url)},1000);
  }
  var onNext = function(url){
      var ts = Math.round(new Date().getTime() / 1000);

    _IG_FetchContent(gomokuServer+"getnext"+url+ "&t="+ts,onNextState,
    {refreshInterval:0});
  }
  function onNextState(responseText){
    x_y = responseText.split(":");
    if(x_y[0]=="1"){
      
        /* if giveup */
      if(x_y[1]=="igiveup"){
        clearInterval(getNextTimer);
        gui.setLocked();
        if($("loading")!=null) $("bg").removeChild($("loading"));
        if($("flag").value==1){
          //black Win!
          var res = document.createElement("span");
          res.id = "res";
          res.className = "content";
          res.innerHTML = "<img src='"+_imgSite+"zhcnblackwin.png'/>";
          gui.addContent(res);
        }
        else{
          //white Win!
          var res = document.createElement("span");
          res.id = "res";
          res.className = "content";
          res.innerHTML = "<img src='"+_imgSite+"zhcnwhitewin.png'/>";
          gui.addContent(res);
        }

        //set Newgame button click
        $("btnNewgame").className = "smallButton";
        $("btnNewgame").onclick = function(){startaNewgame()};
        gui.removelAreaButton("btnGiveup");
        return;
      }
      if(Smov(x_y[1])){
        var stone = x_y[1].split("_");
        stone = {
          x:parseInt(stone[0],10),
          y:parseInt(stone[1],10)
        };
        $("bg").removeChild($("loading"));
        //set Give up button click
        $("btnGiveup").className = "smallButton";
        $("btnGiveup").onclick = function(){iGiveup()};
        clearInterval(getNextTimer);
      // recode
      __opstone[stone.x][stone.y] = 1;
      //change player
      playing = __opstone;
      judge(stone,($("flag").value)^1);
      }
    }
  }
  
  /* Server mov */
  function Smov(x_y){
    if(gui.tmoveStone(x_y)){
      gui.unLocked();
      return 1;
    }
    return 0;
  }
  function restart(){
    /* Create two Players */
    gui.refresh();
    __mystone = _.createPlayer();
    __opstone = _.createPlayer();
    if($("res")!=null){
      $("bg").removeChild($("res"));
    }
  }
  function startaNewgame(){
    if($("res")!=null){
      $("bg").removeChild($("res"));
      gui.refresh();
    }
    
      /* Create two Players */
    __mystone = _.createPlayer();
    __opstone = _.createPlayer();
    
    _p.setPopupImgurl(_imgSite+"zhcnPopupStartanewgame.png",
      250);
    _p.createButton(_imgSite+"zhcnbigButCreateGame.png",
      "Create game",function(){
        _p.goOutAndDo(onCreateGame);
        });
    _p.createButton(_imgSite+"zhcnbigButJoinGame.png",
      "Join game",function(){
        _p.goOutAndDo(onJoinGame);
      });
    _p.show();

    
  }
  //click createButton event
  function onCreateGame(){
    var waiting = document.createElement("span");
    waiting.id = "waiting";
    waiting.innerHTML = "初始化中...";
    {
    var textfield = document.createElement("input");
    textfield.id = "rdnum_textfield";
    textfield.className = "textfield";
    textfield.type = "text";
    textfield.value = "输入创建者给你的数字..";
    textfield.readOnly = 1;
    textfield.style.backgroundImage = "url("+_imgSite+"loading.gif)";
    textfield.style.backgroundRepeat = "no-repeat";
    textfield.style.backgroundPosition = "left center";
    textfield.value = "正在请求...";
    }
    _p.addElement(textfield);
    _p.addElement(waiting);
    _p.show();
        var ts = Math.round(new Date().getTime() / 1000);

    _IG_FetchContent(gomokuServer+"creategame?t="+ts,createGameState,
      {refreshInterval:0});
  }
  function createGameState(responseText){
    $("waiting").innerHTML = 
    "复制这串数字然后发给你的朋友.<br>等待游戏开始吧.";
    textfield = $("rdnum_textfield");
    textfield.style.color = "#000000";
    textfield.value = responseText;
    textfield.style.backgroundImage = "";
    $("rdnum").value = responseText;
    setJoinstatTimer(responseText);
  }
  var setJoinstatTimer = function(rdnum){
    waitForjoinTimer = setInterval(function(){
        var ts = Math.round(new Date().getTime() / 1000);

      _IG_FetchContent(gomokuServer+"waitforjoin?rdnum="+rdnum+ "&t="+ts,
      waitForjoinstat,{refreshInterval:0})},1500); 
  }
  var waitForjoinstat = function(responseText){
    if(!!!$("waiting")) clearInterval(waitForjoinTimer);
    if(responseText=="1"){
      clearInterval(waitForjoinTimer);
      $("waiting").innerHTML = "你朋友来喽,\
      游戏开始!<br>你是黑色.";
      //set black
      $("flag").value = 1;
      gui.unLocked();
      //set btnNewgame cannot Click
      $("btnNewgame").className = "smallButtonAct";
      $("btnNewgame").onclick = "javascript:void(null);";
      //add give up button
      var btnGiveup = gui.createButton("btnGiveup",_imgSite+"zhcnbutgiveup.png",
      1,0,"Give up",function(){iGiveup()});
      if(isIE){
	    btnGiveup.style.position="absolute";
        btnGiveup.style.top = "0px";
        btnGiveup.style.left = "45px";
      }
      setTimeout(_p.cencel,3000);
    }
    else if(responseText=="0"){
      if($("waiting").innerHTML.indexOf("cannot")>0)
        $("waiting").innerHTML =  "把这串数字发给你的朋友.\
        <br>然后等待游戏开始.";
      if($("waiting").innerHTML.indexOf("......")>0){
        $("waiting").innerHTML =  "把这串数字发给你的朋友.\
        <br>然后等待游戏开始.";
      }else{
        $("waiting").innerHTML += ".";
      }
    }else{
       $("waiting").innerHTML = "不能连接服务器, \
       请稍后再试.";
    }
  }
  /* Joingame */
  function onJoinGame(){
    var textfield = document.createElement("input");
    textfield.id = "joingame_textfield";
    textfield.className = "textfield";
    textfield.type = "text";
    textfield.value = "输入创建者给你的数字..";
    textfield.onclick = function(){
      textfield.style.color = "#000000";
      textfield.value = "";
    }
    _p.addElement(textfield);
    
    var waiting = document.createElement("span");
    waiting.id = "waiting";
    waiting.innerHTML = "请输入朋友给你的数字...";
    _p.addElement(waiting);
    
    _p.createButton(_imgSite+"zhcnbigButJoinGame.png",
      "Join game",function(){
        onrealJoinGame()
      });
    _p.show();

  }
  /* send rdnum to server and wait for game start */
  function onrealJoinGame(){
    var textfield = $("joingame_textfield");
    if(textfield.value==""){
        $("waiting").innerHTML  = "请输入朋友给你的数字...";
        return;
    }
    $("waiting").innerHTML  = "等待服务器反馈...";
    rdnum = textfield.value;
    $("rdnum").value = textfield.value;
    var ts = Math.round(new Date().getTime() / 1000);
    var url = "?rdnum=" + rdnum + "&t="+ts;
    _IG_FetchContent(gomokuServer+"joingame"+url,joingameState,{refreshInterval:0});
  
    }
  
  /* sent rdnum then */
  function joingameState(responseText){
    if(responseText=="1"){
      $("waiting").innerHTML = 
      "连接已成功! 你是白色.";
      //set White
      $("flag").value = 0;
      $("btnNewgame").className = "smallButtonAct";
      $("btnNewgame").onclick = "javascript:void(null);";
      setTimeout(_p.cencel,3000);
      setTimeout(getNext,3500);
      //add give up button
      var btnGiveup = gui.createButton("btnGiveup",_imgSite+"zhcnbutgiveup.png",
      1,0,"Give up",function(){iGiveup()});
      if(isIE){
	    btnGiveup.style.position="absolute";
        btnGiveup.style.top = "0px";
        btnGiveup.style.left = "45px";
      }
    }else if(responseText == "2"){
      $("waiting").innerHTML = 
        "连接出错! 找不到游戏! 请重试.";
    }
    else{
      $("waiting").innerHTML = 
        "服务器出错.请重试.";
    }
  }
  /* I give up */
  var iGiveup = function(){
    gui.setLocked();
    /* send to server */
    var url = "?rdnum=" + $("rdnum").value + "&flag=" + $("flag").value + 
    "&stone=igiveup";
    if($("flag").value==0){
      //black Win!
      var res = document.createElement("span");
      res.id = "res";
      res.className = "content";
      res.innerHTML = "<img src='"+_imgSite+"zhcnblackwin.png'/>";
      gui.addContent(res);
    }
    else{
      //white Win!
      var res = document.createElement("span");
      res.id = "res";
      res.className = "content";
      res.innerHTML = "<img src='"+_imgSite+"zhcnwhitewin.png'/>";
      gui.addContent(res);
    }
    $("btnNewgame").className = "smallButton";
    $("btnNewgame").onclick = function(){startaNewgame()};
    gui.removelAreaButton("btnGiveup");
    stonedownTimer=setInterval(function(){oniGiveup(url)},1000); 
  }
  var oniGiveup = function(url){
    var ts = Math.round(new Date().getTime() / 1000);
    _IG_FetchContent(gomokuServer+"stonedown"+url+ "&t="+ts,oniGiveupstat,
    {refreshInterval:0});
  }
  var oniGiveupstat = function(responseText){
    if(responseText=="1"){
      clearInterval(stonedownTimer);
    }
  }
   /* show Helper */
  var showHelp = function(){
    var Content = document.createElement("div");
    /* html */
    Content.innerHTML = "<h1>什么是五子棋？</h1> \
      <p><a href=\"http://code.google.com/p/gomokuonline/\" target=\"_blank\"/> \
      <img src='"+_imgSite+"logo.png' align=\"left\"/></a><strong>五子棋 \
      </strong>是一种两人对弈的纯策略型棋类游戏。<br/>五子棋的棋子分为黑白两色， \
      棋盘采用15×15的五子棋专用棋盘或19×19的围棋的棋盘，棋子放置于棋盘线交叉点上。 \
      </p><p>Gomoku规则：<br>黑白双方轮流落子。<br> \
      盘上第三手棋后执白方有权选择交换。<br/> \
      首先在横、竖、斜方向上成五（连续五个己方棋子）者为胜。</p> \
      <p align=\"center\" class=\"version\">gomoku Online \
      由 mrzenix 开发<br />当前版本 1.02</p>";
    _ns.setTitleImgurl(_imgSite+"enTitleHelp.png");
    _ns.addElement(Content);
    _ns.show();
  }
}